package cn.ava.ymcc.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class TokenForwordFeignInterceptor implements RequestInterceptor {

    //请求头中的token
    private static final String AUTHORIZATION_HEADER = "Authorization";

    @Override
    public void apply(RequestTemplate requestTemplate) {
        //1.拿到当前请求
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (servletRequestAttributes != null) {
            HttpServletRequest request = servletRequestAttributes.getRequest();
            //2.得到请求头中的token
            String token = request.getHeader(AUTHORIZATION_HEADER);
            if(StringUtils.hasLength(token)){
                //3.设置给下一个请求头
                requestTemplate.header("Authorization",token);
            }
        }
    }
}